function totalSeconds(time) {
	var values, sec, factor;
	
	values = time.split(":");
	sec = 0;
	factor = 1;
	
	for(i=(values.length-1); i>=0; i--) {
		sec += parseInt(values[i])*factor;
		factor *= 60;
	}
	
	return sec;
}

var api_lastfm, callback, port;

api_lastfm = "0bcccfa21e04d9cbb01dfe498a8203e1";
callback = chrome.extension.getURL("auth_callback.html");
port = chrome.extension.connect({name: "music_listener"});

port.onMessage.addListener(function(msg) {
	if(document.getElementById("playerSongTitle") != null) {
		var trackName, artistName, albumName, currentTime, duration, isPaused;
		
		trackName = document.getElementById("playerSongTitle").firstChild.textContent;
		artistName = document.getElementById("playerArtist").firstChild.textContent;
		albumName = $(".albumViewAlbumTitle").html();
		currentTime = totalSeconds($("#currentTime").html());
		duration = totalSeconds($("#duration").html());
		isPaused = false;
		
		if(isNaN(duration)) {
			duration = 0;
		}
		
		if($("#playPause").attr("title") == "Paused") {
			isPaused = true;
		}
	
		port.postMessage({"trackName":trackName, "artistName":artistName, "albumName":albumName, 
			"currentTime":currentTime, "duration":duration, "isPaused":isPaused});
	}
});

chrome.extension.sendRequest({action:"need_login"}, function(response) {
	if(response.need == true) {
		var login = confirm("Would you like to log into Last.FM for scrobbling?");

		if(login) {
			window.open("http://www.last.fm/api/auth/?api_key=" + api_lastfm + "&cb=" + callback);
		}
	}
});